package com.cib.process.chat.core;

import com.alibaba.fastjson.JSON;
import com.cib.process.bean.ChannelType;
import com.cib.process.bean.ChatTokenBean;
import com.cib.process.bean.ChatVisitBean;
import com.cib.process.mapper.ChatMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.stream.Collectors;

public class BusnoChatVisitSelector extends AbstractChatVisitSelector {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private ChatMapper chatMapper;

    @Override
    public boolean isVisit(String token, String userId) {
        List<ChatVisitBean> chatVisitBeans=null;
        String chat_visit =  redisTemplate.opsForValue().get("CHAT_VISIT");
        if (StringUtils.isBlank(chat_visit)){
            chatVisitBeans = chatMapper.findVisitAll();
            //将禁用人的名单加入到redis
            if (chatVisitBeans!=null&&chatVisitBeans.size()>0){
                String s = JSON.toJSONString(chatVisitBeans);
                redisTemplate.opsForValue().set("CHAT_VISIT",s);
            }
        }else{
            chatVisitBeans=JSON.parseArray(chat_visit,ChatVisitBean.class);
        }
        //枚举类
        final ChannelType type=ChannelType.instanceOf(token);
        if (type!=null){
            switch (type){
                case IVR:
                    // 指定用户不能访问智能客服。
                    long count = chatVisitBeans.stream().filter(p -> userId.equals(p.getBusno()) && token.equals(p.getChannel())).count();
                    if (count>0){
                        return false;
                    }
                    break;
                case WBG:
                    //可以访问但是前提是该用户的状态是可以访问的
                    List<ChatVisitBean> collect = chatVisitBeans.stream().filter(p -> userId.equals(p.getBusno()) && token.equals(p.getChannel())).collect(Collectors.toList());
                    if (collect.size()<1||collect.get(0).getIs_visit().equals("1")){
                        return false;
                    }
                    break;

            }
        }
        return true;
    }
}
